package wicket.example.components.captcha;


import jj.play.ns.nl.captcha.Captcha;

import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.resource.DynamicImageResource;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;

public class CaptchaPage extends WebPage {

	private static final long serialVersionUID = 1L;

	private transient Captcha cap = null;
	
	public CaptchaPage() {
		
		final TextField<String> captchaAnswer = new TextField<String>("captchaAnswer", new Model<String>(StringUtils.EMPTY));
		captchaAnswer.add(new IValidator<String>(){

			private static final long serialVersionUID = 1L;

			@Override
			public void validate(IValidatable<String> validatable) {
				if (!StringUtils.equalsIgnoreCase(cap.getAnswer(), validatable.getValue())){
					captchaAnswer.error("Error value!");
				} else {
					captchaAnswer.info("Right value!");
				}
			}
			
		});
		captchaAnswer.setOutputMarkupId(true);
		
		Form<Void> form = new Form<Void>("form");
		this.add(form);
		form.add(captchaAnswer);
		
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		form.add(feedback);
		
		final NonCachingImage img = new NonCachingImage("img");
		img.setOutputMarkupId(true);
		img.setImageResource(new DynamicImageResource() {

			private static final long serialVersionUID = 1L;

			@Override
			protected byte[] getImageData(Attributes attributes) {
				cap = CaptchaGenerator.getCapthca();
				return CaptchaGenerator.getImage(cap);
			}
		});
		form.add(img);
		
		AjaxSubmitLink submitLink = new AjaxSubmitLink("submitLink", form) {

			private static final long serialVersionUID = 1L;
			
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				target.add(feedback, captchaAnswer, img);
			}
			
			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				target.add(feedback, captchaAnswer, img);
			}
			
		};
		form.add(submitLink);
		
		
	}

}
